﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TomatoClock.Models;
using TomatoClock.Services;
using TomatoClock.Utilities;
using TomatoClock.ViewModels;
using MaterialSkin.Controls;
using MaterialSkin;
using System.Reflection;
using System.Windows.Forms.DataVisualization.Charting;
using System.Reflection.Emit;
using System.Drawing.Drawing2D;
using Microsoft.VisualBasic.ApplicationServices;
using User = TomatoClock.Models.User;
using System.Diagnostics;

namespace TomatoClock.Views
{
    public partial class MainForm : MaterialForm
    {

        private MainViewModel viewModel;
        private Data data;
        private readonly MaterialSkinManager materialSkinManager;
        private AchievementsControl achievementsControl;
        private ProcessManagerControl processManagerControl;
        private RankingControl rankingControl;

        private float x;//定义当前窗体的宽度
        private float y;//定义当前窗体的高度

        public MainForm(MainViewModel viewModel)
        {


            this.viewModel = viewModel;
            //MessageBox.Show("viewMode1:Curuser id=" + viewModel.CurrentUser.UserId);
            InitializeComponent();


            materialSkinManager = MaterialSkinManager.Instance; // 初始化 MaterialSkinManager 实例
            materialSkinManager.AddFormToManage(this);  // 将要应用 Material Design 的窗体添加到管理列表中
            materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;   // Theme 属性用来设置整体的主题
            materialSkinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE); // ColorScheme 属性来设置配色方案

            FontChanger.ChangeMaterialSkinFont(this, new Font("Arial", 12, FontStyle.Bold));

            ShowTimerPage(new TomatoTimerSetterControl(viewModel));
            ShowUserPage(userPageControl1);

            x = this.Width;
            y = this.Height;
            setTag(this);

            //得到当前用户数据
            this.data = getMainFormData();
            if (data != null) { }//MessageBox.Show("用户id：" + data.UserId + "每日收成：" + data.TomatoNum); 
            else { }//MessageBox.Show("data is null"); return; 

            this.processManagerControl = new ProcessManagerControl(viewModel);//process页面初始化
            this.achievementsControl = new AchievementsControl(); // 确保 achievementsControl 被初始化
            this.rankingControl = new RankingControl(viewModel.dataService.GetUserFocusTimeSumRankList());

            //统计数据页面加载相关
            LoadStatis();
            // 添加这行代码以初始化图表数据
            InitializeChartData();

            //成就界面加载相关
            load();

            //排行榜界面加载相关
            rankingload();

            //加载processPage
            initializeProcessManagerControl();

        }
        private void TestSQL()
        {
            List<User> users = viewModel.dataService.GetUserFocusTimeSumRankList();
            for (int i = 0; i < users.Count; i++)
            {
                Debug.WriteLine($"UserID: {users[i].UserId}");
            }
        }

        private void SetCustomFont(Control control, Font newFont)
        {
            control.Font = newFont;
            foreach (Control childControl in control.Controls)
            {
                SetCustomFont(childControl, newFont);
            }
        }

        public Data getMainFormData() { return viewModel.dataService.GetData(viewModel.CurrentUser.UserId); }

        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            ShowPage(new HomeControl()); // 默认显示主页内容
        }

        public void ShowPage(UserControl page)
        {
        }

        public void ShowTimerPage(UserControl page)
        {
            TimerPanel.Controls.Clear();
            page.Dock = DockStyle.Fill;
            page.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
            TimerPanel.Controls.Add(page);
            page.BringToFront();
        }

        public void ShowUserPage(UserControl page)
        {
            panel1.Controls.Clear();
            page.Dock = DockStyle.Fill;
            page.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
            panel1.Controls.Add(page);
            page.BringToFront();
        }

        public void initializeProcessManagerControl()
        {
            ProcessPage.Controls.Add(processManagerControl);
            processManagerControl.Dock = DockStyle.Fill;
            //MessageBox.Show("加载进程监控页面");
            processManagerControl.Invalidate();
            processManagerControl.Update();
        }

        private void setControls(float newx, float newy, Control cons)
        {
            //遍历窗体中的控件，重新设置控件的值
            foreach (Control con in cons.Controls)
            {
                //获取控件的Tag属性值，并分割后存储字符串数组
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    //根据窗体缩放的比例确定控件的值
                    con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距
                    Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / x;
            float newy = (this.Height) / y;
            setControls(newx, newy, this);
        }



        private void load()//object sender, EventArgs e  用于成就界面初始化
        {
            achievementsControl.setCurAchievements(viewModel.dataService.GetAchievementsForUser(viewModel.CurrentUser.UserId));
            achievementsControl.setMissAchievements(viewModel.dataService.GetMissingAchievements(viewModel.CurrentUser.UserId));
            achievementsControl.setAllAchievements(viewModel.dataService.GetAllAchievements());
            achievementsControl.setViewModel(viewModel);

            // 将 AchievementsControl 添加到 AchievementPanel
            AchievementPanel.Controls.Clear(); // 清除以前的控件
            AchievementPanel.Controls.Add(achievementsControl);
            achievementsControl.Dock = DockStyle.Fill; // 设置 Dock 样式，使其填满整个 TabPage

            // 调用 DisplayAchievements 显示成就
            achievementsControl.DisplayAchievements();
        }

        private void rankingload()//object sender, EventArgs e  用于成就界面初始化
        {
            rankingControl.setUser(viewModel.dataService.GetUserFocusTimeSumRankList());
            rankingControl.setViewModel(viewModel);

            // 将 AchievementsControl 添加到 AchievementPanel
            RankingPanel.Controls.Clear(); // 清除以前的控件
            RankingPanel.Controls.Add(rankingControl);
            rankingControl.Dock = DockStyle.Fill; // 设置 Dock 样式，使其填满整个 TabPage

            // 调用 DisplayAchievements 显示成就
            rankingControl.DisplayUser();
        }
        private void UserPage_Load(object sender, EventArgs e)
        {
            userPageControl1.SetUser(viewModel.CurrentUser);
            userPageControl1.DisplayGender(viewModel.CurrentUser);
        }

        private void label15_Click(object sender, EventArgs e)
        {
        }

        private void LoadStatis()
        {
            taskNumSumLabel.Text = data.TaskNumSum.ToString();
            focusTimeSumLabel.Text = data.FocusTimeSum.ToString();
            taskNumLabel.Text = data.TaskNum.ToString();
            focusTimeLabel.Text = data.FocusTimeSum.ToString();
            DateLabel.Text = DateTime.Now.ToString("yyyy-M-d");
        }

        private void InitializeChartData()
        {

            var data = viewModel.dataService.GetFocusWithDayOfWeek(viewModel.CurrentUser.UserId);

            // 确保获取到数据
            if (data == null || data.Count == 0)
            {
                // 在这里处理没有数据的情况，可以给出提示或者不执行任何绘图操作
                // 例如：
                MessageBox.Show("没有可用的数据。");
                return;
            }

            // 确保 ChartArea 存在
            if (WeekChart.ChartAreas.Count == 0)
            {
                WeekChart.ChartAreas.Add(new ChartArea("ChartArea1"));
            }

            WeekChart.Series.Clear();
            Series series = new Series("Focus Time")
            {
                ChartType = SeriesChartType.Column
            };

            WeekChart.Series.Add(series);

            // 添加自定义标签
            string[] daysOfWeek = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天" };
            for (int i = 0; i < daysOfWeek.Length; i++)
            {
                CustomLabel customLabel = new CustomLabel();
                customLabel.Text = daysOfWeek[i];
                customLabel.FromPosition = i + 0.5;
                customLabel.ToPosition = i + 1.5;
                WeekChart.ChartAreas[0].AxisX.CustomLabels.Add(customLabel);
            }

            // 添加数据点
            int dayIndex = 1;
            foreach (var item in data)
            {
                series.Points.AddXY(dayIndex, item.Value);
                dayIndex++;
            }

            // 设置横轴的标签样式和标题
            WeekChart.ChartAreas[0].AxisX.LabelStyle.Interval = 1;
            WeekChart.ChartAreas[0].AxisX.MajorGrid.Enabled = false; // 可选：禁用网格线
            WeekChart.ChartAreas[0].AxisX.LabelStyle.Angle = 0; // 确保标签水平显示
            WeekChart.ChartAreas[0].AxisX.LabelStyle.IsStaggered = false; // 禁用交错标签
            WeekChart.ChartAreas[0].AxisX.Title = "Day of the Week"; // 设置横轴标题

            // 设置纵轴的标签样式和标题
            WeekChart.ChartAreas[0].AxisY.Title = "Minutes"; // 设置纵轴标题
            WeekChart.ChartAreas[0].AxisY.LabelStyle.Interval = 60; // 设置纵轴标签的间隔
            WeekChart.ChartAreas[0].AxisY.MajorGrid.Enabled = true; // 启用纵轴网格线以增强可读性

            // 调整边距以显示完整标签
            WeekChart.ChartAreas[0].AxisX.IsLabelAutoFit = false; // 禁用自动适应标签
            WeekChart.ChartAreas[0].AxisX.LabelStyle.Font = new Font("Arial", 8); // 设置标签字体大小
            WeekChart.ChartAreas[0].AxisX.LabelStyle.TruncatedLabels = false; // 禁用标签截断
            WeekChart.ChartAreas[0].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.None; // 禁用标签自动调整样式
            WeekChart.ChartAreas[0].AxisX.Interval = 1; // 确保每个标签都显示
        }

        private void taskNumSumLabel_Click(object sender, EventArgs e)
        {

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 获取当前选中的选项卡
            TabPage selectedTab = materialTabControl1.SelectedTab;

            // 调试输出
            //MessageBox.Show($"Selected tab: {selectedTab.Text}, Achievement count: {this.achievementsControl.achievementCount}");

            // 检查选项卡的名称
            if (selectedTab.Text == "成就" && this.achievementsControl.achievementCount == 0)
            {
                //MessageBox.Show("选中成就界面且没有成就");
                var unlockAchievementDialog = new UnlockAchievementDialog();
                unlockAchievementDialog.ShowDialog();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TestSQL();
        }
        private int colorSchemeIndex;
        private void button1_Click_1(object sender, EventArgs e)
        {
            colorSchemeIndex++;
            if (colorSchemeIndex > 3)
                colorSchemeIndex = 0;
            updateColor();
        }
        private void updateColor()
        {
            //These are just example color schemes
            switch (colorSchemeIndex)
            {
                case 0:
                    materialSkinManager.ColorScheme = new ColorScheme(
                        Primary.Grey700,
                       Primary.Grey900,
                       Primary.Grey600,
                       Accent.Amber400,
                       TextShade.WHITE);
                    break;

                case 1:
                    materialSkinManager.ColorScheme = new ColorScheme(
                       Primary.Blue600,
                       Primary.Blue800,
                       Primary.Blue300,
                       Accent.Red100,
                       TextShade.WHITE);
                    break;

                case 2:
                    materialSkinManager.ColorScheme = new ColorScheme(
                        Primary.Green600,
                        Primary.Green700,
                        Primary.Green200,
                        Accent.Red100,
                        TextShade.WHITE);
                    break;
                case 3:
                    materialSkinManager.ColorScheme = new ColorScheme(
                        ColorTranslator.FromHtml("#f09819"),
                        ColorTranslator.FromHtml("#c07819"),
                        ColorTranslator.FromHtml("#f09819"),
                        ColorTranslator.FromHtml("#ff5858"),
            TextShade.WHITE);
                    break;
            }
            Invalidate();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            materialSkinManager.Theme = materialSkinManager.Theme == MaterialSkinManager.Themes.DARK ? MaterialSkinManager.Themes.LIGHT : MaterialSkinManager.Themes.DARK;
        }
    }

    public class FontChanger
    {
        public static void ChangeMaterialSkinFont(Control control, Font newFont)
        {
            Type type = control.GetType();
            PropertyInfo textFontProperty = type.GetProperty("FONT", BindingFlags.NonPublic | BindingFlags.Static);
            if (textFontProperty != null)
            {
                textFontProperty.SetValue(null, newFont);
            }
        }
    }
}
